#!/bin/bash
# Utiliit aitamaks erinevaid linuxi distroid lihtsamini üles seada
# This is a main script
# 
# TODO
# Write code for running functions as root
# Write code for AfterRun
# 

# 

PROGRAM="Utiliit (main)"
VERSION="0.0.1-dev"
NeedsRoot=""
debug=no # yes or no

function CheckSystem()
{
	# we use lsb_release to detect distro
	function CheckLsb_release()
	{
		print "## Checking System ##" bluebold
		if [ ! -e /usr/bin/lsb_release ]; then 
			print "lsb_release does not exist, os might be fedora" normal
			print "anyway, exiting from script" normal
			print "lsb_release doesn't exist and if you are using fedora then" red
			print "try using$ENDCOLOR yum install redhat-lsb$RED to install it" red
			Terminate "lsb_release not found or installed"
		else
			print "lsb_release Verified" green
		fi
	}
	
	# Check Distro
	function CheckDistro()
	{
		distroid=`lsb_release -is`
		release=`lsb_release -sr`
		local message_yes="Found supported system: $distroid $release"
		local message_no="Found unsuported system: $distroid $release"
		if [ "$distroid $release" = "Ubuntu 11.10" ]; then
			print "$message_yes" green
		elif [ "$distroid $release" = "Fedora 16" ]; then #TODO: Needs to be tested !
			print "$message_yes" green
		else
			print "$message_no" red
			Terminate "user is using unsuported system"
		fi
	}
	
	# Check Architecture
	function CheckArch()
	{
		if [ $(uname -i) = "i386" ]; then
			print "Architecture Verified (32-bit)" green
		elif [ $(uname -i) = "x86_64" ]; then
			print "Architecture Verified (64-bit)" green
		else
			print "This $(uname -i) architecture is not yet supported" red
			Terminate "Architecture not supported"
		fi
	}
	
	
	
	function CheckZenity()
	{
		# Check Zenity
		if [ -e /usr/bin/zenity ]; then
			print "Zenity Verified" green
		else
			print "Zenity is needed for $PROGRAM to run properly." red
			#TODO use functions from func_* file to install zenity
			#sudo yum -y install --nogpgcheck zenity
			#if [ ! -e /usr/bin/zenity ]; then
				#echo -e $RED"Installation of zenity failed"$ENDCOLOR
				Terminate "Zenity not installed"
			#fi
		fi
	}
	
	#Run all functions
	CheckLsb_release
	CheckDistro
	CheckArch
	CheckZenity
	
}

function DownloadFunc()
{
	print "## Downloading func_${distroid,,} ##" bluebold
	if [ "$use_local_files" = "yes" ]; then
		print "using local file" yellow
		cp "./func_${distroid,,}" $WORKINGDIR
	else
		GetFile $BASE_URL"func_"${distroid,,} quiet
		print "func_${distroid,,} downloaded" green
	fi
}

function StartGUI() #Create GUI with zenity
{
	function GenMenu()
	{
		print "## Generating menu for $@ ##" bluebold
		if [ "$@" == "M_" ];then
			local type="--radiolist"
		else
			local type="--checklist"
		fi
		
		# ilma kirjeldusteta funktsioonide nimed
	    funkts=$(grep "^function $@" "$WORKINGDIR/func_${distroid,,}" | sed -n -r -e "s/(^function )([[:alnum:]_]*)(\(\)).*/\2/gp")
		debug "funkts=$funkts"
		
	    # kirjeldustega funktsioonide nimed
	    funkts_desc=$(grep "^function $@" "$WORKINGDIR/func_${distroid,,}" | sed -n -r -e "s/(^function )([[:alnum:]_]*)(\(\))/\2/gp")
	    debug "funkts_desc=$funkts_desc"
	
	    # kui on kirjeldus olemas, siis näitab seda kasutajaliideses
	    # kui kirjeldust pole, siis näitab funktsiooni nime
	    # tagastab kõik linnukestega funktsioonide nimed
	    IFS=$'\n'
	    selected=`for rida in $funkts_desc
	    do
	    	echo false
	    	set -- $rida
	    	IFS="#"; declare -a andmed=($*)
	    	nimi=${andmed[0]%% }
	    	seletus=${andmed[1]## }
	    	if [ "$seletus" != "" ]; then
	    		echo $nimi
	    		echo $seletus
	    	else
	    		echo $nimi
	    		echo $nimi
	    	fi
	
	    done | zenity --width=600 --height=500 --title="$PROGRAM $VERSION" --text="Vali soovitud kohandused siit..." --list $type --column="Olek" --column="Nimi" --column="Seletus" --hide-column=2 --hide-header 2> /dev/null`
	    # kui vajutati "olgu"
	    if [ $? = 0 ]; then
	    debug "selected=$selected"
	
		    # see pole vist kõige parem nii moodi kõiki funktsioone käivitada
		
		    #nüüd laseme root kasutajat vajavad käsud käima
		    #if [ "$VajabRuudu6igust" != "" ]; then
				#fun=$(echo $VajabRuudu6igust | tr ":" "\n")
			    	#for x in $fun; do
			    		#echo -e "\nkäivitan ruuduna valitud funtsioonid\n"
			    		#echo $x
			    		#gksudo "/bin/bash -c 'source $asukoht/funktsioonid; $x'" # tundub et isegi töötab
			    	#done
			        #VajabRuudu6igust=""
		    #fi
		elif [ "$@" == "M_" ]; then
			Terminate "user wanted."
	    fi
	#Done
	#Main
	}
	
	function RunFunctions()
	{
	local func_local=$(echo $selected | tr "|" "\n")
    for x in "$func_local"; do
    	debug "Käivitan $x"
    	${x}
    done

	}
	
	#Run functions
	GenMenu "M_"
	RunFunctions
	GenMenu "$Prefix"
	RunFunctions
	#RunFunctionsAsRoot
	#AfterRun
	StartGUI		
}

function Terminate()
{
	print "## Terminating script because $1 ##" redbold
    exit 1
}

function Complete()
{
	print "## Completed. ##" bluebold
	zenity --info --text="Completed. Click Ok to Exit."
	exit 0;
}

function zudo() # replace gksu and gksudo 
{
	zenity --password --title="Get sudo for $@" | sudo -S "$@" &> /dev/null
}

function GetFile() #make wget easier to use
{	# usage:
	# GetFile "file url"		GUI downloader (not working correctly)
	# GetFile "file url" cli	CLI downloader (not working correctly)
	# GetFile "file url" quiet	Don't output anything (use that)
	
	if [ "$2" = "cli" ] ;then
		#CLI downloader
		function progressfilt() #Because i don't know how to use curl !
		{
		    local flag=false c count cr=$'\r' nl=$'\n'
		    while IFS='' read -d '' -rn 1 c
		    do
		        if $flag
		        then
		            printf '%c' "$c"
		        else
		            if [[ $c != $cr && $c != $nl ]]
		            then
		                count=0
		            else
		                ((count++))
		                if ((count > 1))
		                then
		                    flag=true
		                fi
		            fi
		        fi
		    done
		}
		wget --progress=bar:force "$1" -P "$WORKINGDIR" 2>&1 | progressfilt
	elif [ "$2" = "quiet" ] ;then
		#Quiet downloader
		wget -q "$1" -P "$WORKINGDIR"
	else
		#GUI downloader
		wget --progress=bar:force "$1" -P "$WORKINGDIR" 2>&1 |\
		zenity --title="File transfer in progress!" \
		--progress \
		--auto-close \
		--auto-kill
	fi
}

function debug() #i needed a simple debuger !
{
	if [ "$debug" = "yes" ]; then print "DEBUGER: $@" yellow; fi
}

function Main()
{
	echo
	print "$PROGRAM $VERSION" bold 
	CheckSystem
	DownloadFunc
	source "$WORKINGDIR/func_${distroid,,}"
	StartGUI
		
}

Main
